import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

/// 右侧有删除按钮,查看密码的文本框
class TextFieldNormal extends StatefulWidget {
  final TextEditingController controller;

  final FocusNode? focusNode;

  /// 左侧标题文本
  final String title;

  /// 左侧标题样式
  final TextStyle? titleStyle;

  /// 左侧文本对齐方式
  final TextAlign? titleTextAlign;

  /// 提示文本内容
  final String hintText;

  /// 提示文本样式
  final TextStyle? hintStyle;

  /// 输入框文本样式
  final TextStyle? contentStyle;

  /// 文本框内容对齐微调
  final EdgeInsetsGeometry contentPadding;

  /// 运行文本框输入最大长度
  final int maxLength;

  /// 是否自动聚焦，默认是false。
  final bool autoFocus;

  /// 是否启用文本框输入
  final bool? enabled;

  /// 是否是密码输入
  final bool isInputPwd;

  /// TextField成为焦点时显示的键盘类型
  final TextInputType keyboardType;

  /// 右侧文本框距左侧宽度
  final double spacing;

  /// 左侧文本最小宽度
  final double minWidth;

  /// 提交事件
  final ValueChanged<String>? onSubmitted;

  /// 编辑完成事件
  final VoidCallback? onEditingComplete;

  /// 删除
  final VoidCallback? onDeleted;

  TextFieldNormal({
    Key? key,
    required this.controller,
    this.focusNode,
    this.title = "",
    this.titleStyle,
    this.titleTextAlign,
    this.hintText = "",
    this.hintStyle,
    this.contentStyle,
    this.contentPadding = const EdgeInsets.symmetric(vertical: 16.0),
    this.maxLength = 50,
    this.autoFocus = false,
    this.enabled = true,
    this.isInputPwd = false,
    this.keyboardType = TextInputType.text,
    this.spacing = 15.0,
    this.minWidth = 65.0,
    this.onSubmitted,
    this.onEditingComplete,
    this.onDeleted,
  }) : super(key: key);

  @override
  _TextFieldNormalState createState() => _TextFieldNormalState();
}

class _TextFieldNormalState extends State<TextFieldNormal> {
  // 控制密码是否明文显示(默认不显示明文)
  bool _isShowPwd = false;

  // 控制删除文本按钮是否显示
  bool _isShowDelete = true;

  @override
  void initState() {
    super.initState();
    //监听输入改变
    widget.controller.addListener(() {
      setState(() {
        _isShowDelete = widget.controller.text.isEmpty;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Offstage(
          offstage: widget.title.isEmpty,
          child: Container(
            padding: EdgeInsets.only(right: widget.spacing),
            constraints: BoxConstraints(
              minWidth: widget.minWidth,
            ),
            child: Text(
              widget.title,
              textAlign: widget.titleTextAlign ?? TextAlign.left,
//              style: widget.titleStyle ?? TextStyles.textDark14,
            ),
          ),
        ),
        Expanded(
          child: Localizations(
            locale: const Locale("en", ""),
            delegates: [
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
            ],
            child: TextField(
              focusNode: widget.focusNode,
              maxLength: widget.maxLength,
              obscureText: widget.isInputPwd ? !_isShowPwd : false,
              autofocus: widget.autoFocus,
              enabled: widget.enabled,
              controller: widget.controller,
              textInputAction: TextInputAction.done,
              keyboardType: widget.keyboardType,
              inputFormatters: _getInputFormatters(),
              decoration: InputDecoration(
                contentPadding: widget.contentPadding,
                hintText: widget.hintText,
//                hintStyle: widget.hintStyle ?? TextStyles.textGray14,
                counterText: "",
                border: InputBorder.none,
                focusedBorder: InputBorder.none,
                enabledBorder: InputBorder.none,
              ),
//              style: widget.contentStyle ?? TextStyles.textNormal14,
              onSubmitted: widget.onSubmitted,
              onEditingComplete: widget.onEditingComplete,
            ),
          ),
        ),
        Offstage(
          offstage: _isShowDelete,
          child: InkWell(
            highlightColor: Colors.transparent,
            splashColor: Colors.transparent,
            child: Icon(Icons.close),
            onTap: () {
              widget.controller.clear();
              if (widget.focusNode != null && widget.enabled!) {
                widget.focusNode?.requestFocus();
              }
              if (widget.onDeleted != null) {
                widget.onDeleted!();
              }
            },
          ),
        ),
        Offstage(
          offstage: !widget.isInputPwd,
          child: Padding(
            padding: const EdgeInsets.only(left: 15.0),
            child: InkWell(
              highlightColor: Colors.transparent,
              splashColor: Colors.transparent,
              child: _isShowPwd
                  ? Icon(Icons.visibility)
                  : Icon(Icons.visibility_off),
              onTap: () {
                setState(() {
                  _isShowPwd = !_isShowPwd;
                });
              },
            ),
          ),
        ),
      ],
    );
  }

  /// 允许的输入格式
  _getInputFormatters() {
    List<TextInputFormatter> list = [];

//    if (widget.keyboardType == TextInputType.numberWithOptions(decimal: true)) {
//      list.add(UsNumberTextInputFormatter());
//    }
    //  数字、手机号限制格式为数字
    if (widget.keyboardType == TextInputType.number ||
        widget.keyboardType == TextInputType.phone) {
      list.add(FilteringTextInputFormatter.digitsOnly);
    }
    // 密码限制不包含汉字（黑名单）
    if (widget.isInputPwd) {
      list.add(FilteringTextInputFormatter.deny(RegExp("[\u4e00-\u9fa5]")));
    }
    // 长度限制
    if (widget.maxLength > 0) {
      list.add(LengthLimitingTextInputFormatter(widget.maxLength));
    }
    return list.length > 0 ? list : null;
  }
}
